package cn.hg.jbsa.admin.controller.system.validator;

import org.apache.shiro.SecurityUtils;

import com.jfinal.core.Controller;

import cn.hg.jboot.core.kit.PasswordKit;
import cn.hg.jboot.core.validator.BaseValidator;
import cn.hg.jbsa.admin.model.JbsaAdmin;
import cn.hutool.core.util.ObjectUtil;

/**
 * @author 胡高
 * @date 2021/12/24
 */
public class JbsaAdminValidator extends BaseValidator {

    /* (non-Javadoc)
     * @see com.jfinal.validate.Validator#handleError(com.jfinal.core.Controller)
     */
    @Override
    protected void handleError(Controller c) {
    }

    /* (non-Javadoc)
     * @see com.jfinal.validate.Validator#validate(com.jfinal.core.Controller)
     */
    @Override
    protected void validate(Controller c) {

        this.validateInteger("bean.orgId", 1, Integer.MAX_VALUE, "orgIdMsg", "必须填写组织机构！");

        this.validateString("bean.accountName", 2, 50, "accountMsg", "账号必须填写2到50长度的字符！");
        this.validateString("bean.nickname", 2, 50, "nameMsg", "昵称必须填写2到50长度的字符！");

        // 如果存在新密码字段，一定要和确认密码匹配
        if (!c.isParaBlank("newPassword")) {
            this.validateString("newPassword", 6, 128, "newPasswordMsg", "新密码必须填写6到128长度的字符!");
            this.validateEqualField("newPassword", "confirmPassword", "newPasswordMsg", "确认密码必须和新密码相同！");
        }

        if (c.isParaBlank("bean.id")) {
            // 新记录必须输入密码
            if (c.isParaBlank("newPassword")) {
                this.addError("newPasswordMsg", "必须输入密码");
            }
        } else {
            // 老记录中存在新密码字段，说明需要重置密码
            if (!c.isParaBlank("newPassword")) {
                this.validateRequired("adminPassword", "adminPasswordMsg", "重置密码时必须填写当前管理员密码！");

                JbsaAdmin admin = (JbsaAdmin) SecurityUtils.getSubject().getPrincipal();
                if (ObjectUtil.isNull(admin)) {
                    this.addError("beanMsg", "登录超时，请重新登录！");
                }

                // 重置密码，必须输入当前管理员的登录密码做验证
                if (!PasswordKit.validatePassword(admin.getSalt(), c.getPara("adminPassword"), admin.getPassword())) {
                    this.addError("adminPasswordMsg", "当前操作员密码不正确！");
                }
            }
        }

        this.validateRequired("bean.status", "statusMsg", "必须填写状态！");

        if (!c.isParaBlank("bean.email")) {
            this.validateEmail("bean.email", "emailMsg", "电子邮件格式不正确！");
        }

        if (!c.isParaBlank("bean.mobile")) {
            this.validateMobilePhone("bean.mobile", "mobileMsg", "手机号码格式不正确！");
        }

        if (!c.isParaBlank("bean.phone")) {
            this.validateTelePhone("bean.phone", "phoneMsg", "电话号码格式不正确！");
        }
    }

}
